import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Select, InputNumber, Button, message, Spin } from 'antd';
import router from 'umi/router';
import { connect } from 'dva';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ supplier, loading }) => ({
  supplier,
  loading: loading.models.supplier,
}))
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      suppId: '',
      supplyInfo: {},
    };
  }

  componentDidMount() {
    const { suppId } = this.props;
    const { name, dispatch, form } = this.props;
    dispatch({
      type: 'supplier/supplyinvoiceGet',
      payload: { suppId },
    }).then(res => {
      this.setState({ suppId });
      if (res.success && res.data) {
        this.setState({ supplyInfo: res.data });
        const getFieldsList = form.getFieldsValue();
        Object.keys(getFieldsList).forEach(key => {
          if (key === 'name') {
            form.setFieldsValue({ name });
          }
          if (res.data[key]) {
            if (key === 'agtsrvInvType' || key === 'serInvType') {
              res.data[key] = form.setFieldsValue({
                [key]: { key: `${res.data[key]}` },
              });
            } else {
              form.setFieldsValue({ [key]: res.data[key] });
            }
          }
        });
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  }

  // 提交
  sumSubmit = e => {
    e.preventDefault();
    const { suppId, supplyInfo } = this.state;
    const { dispatch, form } = this.props;
    const data = {};
    let submitData = {};
    form.validateFieldsAndScroll((error, values) => {
      if (!error) {
        Object.keys(values).forEach(key => {
          if (values[key] && values[key].key) {
            data[key] = values[key].key;
          } else {
            data[key] = values[key] ? values[key] : '';
          }
        });

        submitData = {
          ...data,
          suppId,
          vno: supplyInfo.vno,
          printInvoiceId: supplyInfo.printInvoiceId,
        };
        dispatch({
          type: 'supplier/suppliyinvoiceUpdate',
          payload: submitData,
        }).then(res => {
          if (res.success) {
            message.success(`${res.message || '修改成功！'}`, 2, () => {
              router.push('/salemanage/supplier/index?activeKey=2');
            });
          } else {
            message.warning(`${res.message || '修改失败！'}`);
          }
        });
      }
    });
  };

  render() {
    const { loading } = this.props;
    const {
      form: { getFieldDecorator },
      invoiceTypeList,
    } = this.props;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    // 下拉选项
    // 发票类型
    const agtsrvInvTypeOL = invoiceTypeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    const serInvTypeOL = invoiceTypeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    return (
      <Spin tip="Loading..." spinning={loading}>
        <Form layout="vertical">
          <Row gutter={64}>
            <Col {...colProps}>
              <FormItem label="供应商名称">
                {getFieldDecorator('name', {
                  rules: [{ required: true, message: '请输入' }],
                  initialValue: '',
                })(<Input placeholder="请输入" disabled />)}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="代收代付票据类型">
                {getFieldDecorator('agtsrvInvType', {
                  rules: [{ required: true, message: '请输入' }],
                })(
                  <HOCSelect
                    placeholder="请选择"
                    style={{ width: '100%' }}
                    labelInValue
                    showSearch
                    optionFilterProp="children"
                  >
                    {agtsrvInvTypeOL}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="代收代付税率">
                {getFieldDecorator('agtsrvTaxRate', {
                  rules: [{ required: true, message: '请输入' }],
                  initialValue: 0,
                })(
                  <InputNumber
                    min={0}
                    max={100}
                    formatter={value => `${value}%`}
                    parser={value => value.replace('%', '')}
                    style={{ width: '100%' }}
                  />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={64}>
            <Col {...colProps}>
              <FormItem label="服务费票据类型">
                {getFieldDecorator('serInvType', {
                  rules: [{ required: false, message: '请选择' }],
                })(
                  <HOCSelect
                    placeholder="请选择"
                    style={{ width: '100%' }}
                    allowClear
                    labelInValue
                    showSearch
                    optionFilterProp="children"
                  >
                    {serInvTypeOL}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="服务费税率">
                {getFieldDecorator('serTaxRate', {
                  rules: [{ required: false, message: '请输入' }],
                  initialValue: 0,
                })(
                  <InputNumber
                    min={0}
                    max={100}
                    formatter={value => `${value}%`}
                    parser={value => value.replace('%', '')}
                    style={{ width: '100%' }}
                  />
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="备注">
                {getFieldDecorator('remark', {
                  rules: [{ required: false, message: '请输入' }],
                })(<Input placeholder="请输入" />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div
          style={{
            marginTop: 100,
            paddingTop: 24,
            textAlign: 'right',
            boxShadow: '0 -1px 2px rgba(0, 0, 0, 0.03)',
            borderTop: '1px solid #e8e8e8',
          }}
        >
          <Button
            onClick={() => router.push('/salemanage/supplier/index?activeKey=2')}
            style={{ marginRight: 10 }}
          >
            取消
          </Button>
          <Button type="primary" onClick={this.sumSubmit}>
            提交
          </Button>
        </div>
      </Spin>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
